package com.shiwenping.reply.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jakewharton.rxbinding2.view.RxView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.shiwenping.reply.R;
import com.shiwenping.reply.adapter.AbstractListAdapter;
import com.shiwenping.reply.adapter.BaseViewHolder;
import com.shiwenping.reply.data.Repository;
import com.shiwenping.reply.databinding.FragmentIndexBinding;
import com.shiwenping.reply.databinding.ItemReplyStringLayoutBinding;
import com.shiwenping.reply.net.ApiManager;
import com.shiwenping.reply.net.RxDownLoadManager;
import com.shiwenping.reply.net.domain.FaqImageListBean;
import com.shiwenping.reply.net.domain.FaqItemResult;
import com.shiwenping.reply.net.domain.FileItemResult;
import com.shiwenping.reply.net.service.AllService;
import com.shiwenping.reply.recycle.OnItemClickListener;
import com.shiwenping.reply.tools.AllUtils;
import com.shiwenping.reply.tools.Path;
import com.shiwenping.reply.view.CateDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.functions.Consumer;
import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author shiwenping
 * @date 17-11-6 下午5:12
 */
@Route(path = Path.MAIN_INDEX)
public class IndexFragment extends BaseFragment<FragmentIndexBinding> {
    /**
     * 数据源
     */
    private List<FaqItemResult> data = new ArrayList<>();

    /**
     * Adapter
     */
    private AbstractListAdapter<BaseViewHolder<ItemReplyStringLayoutBinding>> adapter;

    private Repository repository;

    private CateDialog cateDialog;

    private ListPopupWindow listPopupWindow = null;

    private KProgressHUD kProgressHUD;

    @Autowired
    public boolean isFile = false;

    private String currCateName = "";

    private ArrayList<String> data_menu = new ArrayList<>();
    @Override
    int resLayout() {
        return R.layout.fragment_index;
    }



    @Override
    public void initViewer() {
        super.initViewer();
        kProgressHUD = KProgressHUD.create(getActivity());
        databinding.toolbar.inflateMenu(R.menu.main_action);
        cateDialog = new CateDialog(getContext(),isFile);
         listPopupWindow = new ListPopupWindow(getContext());
    }

    @Override
    public void initListener() {
        super.initListener();
        cateDialog.setOnSelectCateListener(cateName -> {
            this.currCateName = cateName;
            databinding.down.animate()
                    .rotation(0)
                    .start();
            databinding.background.animate().alpha(0)
                    .start();
            databinding.title.setText(cateName);
            if (isFile)
            {
                getFileList(true);
            }else {
                getList(true);
            }
        });
        databinding.recycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onClick(RecyclerView.ViewHolder viewHolder, int position) {
                Toast.makeText(getActivity(), "点击了:" + position, Toast.LENGTH_SHORT).show();
            }
        });
        databinding.xrefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                if (isFile)
                {
                    getFileList(false);
                }else {
                    getList(false);
                }
            }
        });
        RxView.clicks(databinding.titleLayout)
                .subscribe(o -> {
                    databinding.down.animate()
                            .rotation(-180)
                            .start();
                    databinding.background.animate().alpha(0.3f)
                            .start();
                    cateDialog.show(databinding.toolbar);
                });
        databinding.background.setOnTouchListener((View v, MotionEvent event) -> {
            if (cateDialog.isShowing())
            {
                databinding.down.animate()
                        .rotation(0)
                        .start();
                databinding.background.animate().alpha(0)
                        .start();
                cateDialog.hide();
                return true;
            }
            return false;
        });
    }
    @Override
    public void initAdapter() {
        super.initAdapter();



        adapter = new AbstractListAdapter<BaseViewHolder<ItemReplyStringLayoutBinding>>(1, getActivity(),
                ContextCompat.getColor(getActivity(), R.color.color_line)) {
            @Override
            public BaseViewHolder<ItemReplyStringLayoutBinding> onCreateViewHolder(ViewGroup parent, int viewType) {

                return new BaseViewHolder<>(inflater.inflate(R.layout.item_reply_string_layout, parent, false));
//                return new RecyclerView.ViewHolder(inflater.inflate(R.layout.item_reply_string_layout, parent, false)) {
//                };
            }

            @Override
            public void onBindViewHolder(BaseViewHolder<ItemReplyStringLayoutBinding> holder, int position) {
                FaqItemResult result = data.get(position);
                int u_id = Integer.parseInt(result.getUser_id());
                int c_id = Integer.parseInt(result.getCid());

                if (u_id == -1 || c_id == -1)
                {
                    holder.databinding.menu.setVisibility(View.GONE);
                }else {
                    holder.databinding.menu.setVisibility(View.VISIBLE);
                }
                holder.databinding.images.removeAllViews();
                holder.databinding.detail.setText(result.getFaq_answer());
                holder.databinding.detail.setMaxLines(2);
                if (!TextUtils.isEmpty(result.getFaq_image_url()) && result.getFaq_image_list() != null)
                {
                    holder.databinding.title.setText(
                            String.format(Locale.CHINESE,"[%d图]%s", result.getFaq_image_list().size()
                                    ,result.getFaq_question()));
                }else {
                    holder.databinding.title.setText(result.getFaq_question());
                }
                holder.itemView.setOnClickListener(v -> {
                    Log.d("HaiChecker","图片:"+result.getFaq_image_url());
                    if (holder.databinding.detail.getLayout()
                            .getEllipsisCount(holder.databinding.detail.getLineCount() - 1) != 0
                            ||(!TextUtils.isEmpty(result.getFaq_image_url())
                            && holder.databinding.images.getChildCount() == 0)) {
                        holder.databinding.detail.setMaxHeight(getResources().getDisplayMetrics().heightPixels);
                        if (!TextUtils.isEmpty(result.getFaq_image_url()) && result.getFaq_image_list() != null) {
                            for (FaqImageListBean faqImageListBean : result.getFaq_image_list()) {
                                ImageView imageView = new ImageView(v.getContext());
                                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                File file = new File(AllUtils.toFileSavePath(faqImageListBean.getUrl()));
                                Log.d("HaiChecker","文件名:"+file.getName());
                                Glide.with(imageView).load(file.getAbsolutePath()).apply(new RequestOptions()).into(imageView);
                                holder.databinding.images.addView(imageView);
                            }
                            holder.databinding.getRoot().requestLayout();
                        }
                    }else {
                        if (holder.databinding.detail.getMaxLines() != 2) {
                            holder.databinding.images.removeAllViews();
                            holder.databinding.detail.setMaxLines(2);
                        }
                    }
                });
                holder.databinding.menu.setOnClickListener(v -> {

//                            int u_id = Integer.parseInt(result.getUser_id());
//                            int c_id = Integer.parseInt(result.getCid());

//                            if (u_id == -1 || c_id == -1)
//                            {
//                               KProgressHUD kProgressHUD = KProgressHUD.create(getContext())
//                                        .setLabel("不能操作当前知识!")
//                                       .setGraceTime(1000)
//                                        .setAutoDismiss(true)
//                                        .show();
//                                new Handler().postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        kProgressHUD.dismiss();
//                                    }
//                                },100);
//                                return;
//                            }

                            data_menu.clear();
                            data_menu.add("删除");
                            data_menu.add("编辑");
                            listPopupWindow.setAdapter(
                                            new ArrayAdapter<String>(v.getContext(), android.R.layout.simple_list_item_1, data_menu));

                            listPopupWindow.setWidth(300);
                            listPopupWindow.setContentWidth(300);
                            listPopupWindow.setAnchorView(v);
                            listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    switch (data_menu.get(position))
                                    {
                                        case "删除":
                                            delFaq(result);
                                            break;

                                            default:
                                                break;
                                    }
                                    listPopupWindow.dismiss();
                                }
                            });
                            listPopupWindow.show();
                        });
            }

            @Override
            public int getItemCount() {
                return data == null ? 0 : data.size();
            }
        };

        databinding.recycler.setLayoutManager(new VirtualLayoutManager(getActivity()));
        DelegateAdapter delegateAdapter = new DelegateAdapter(
                (VirtualLayoutManager) databinding.recycler.getLayoutManager()
        );

        delegateAdapter.addAdapter(adapter);
        databinding.recycler.setAdapter(delegateAdapter);
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        databinding.xrefreshView.setPullRefreshEnable(true);
        repository = Repository.getRepository(getContext());
//        databinding.xrefreshView.startRefresh();
        if (isFile)
        {
            getFileList(true);
        }else {
            getList(true);
        }

    }

    private void getList(boolean isLocal) {
        Log.d("HaiChecker","是否获取本地缓存数据:"+isLocal);
        repository.getFaqList(isLocal,currCateName)
                .flatMap(results -> {
                    List<Observable<String>> observables = new ArrayList<>();
                    for (FaqItemResult result : results) {
                        if (!TextUtils.isEmpty(result.getFaq_image_url())) {
                            observables.add(RxDownLoadManager.download( result.getFaq_image_url()));
                        }
                        if (result.getFaq_image_list() != null) {
                            for (FaqImageListBean faqImageListBean : result.getFaq_image_list()) {
                                observables.add(RxDownLoadManager.download( faqImageListBean.getUrl()));
                            }
                        }
                    }
                    data.clear();
                    data.addAll(results);
                    Log.d("HaiChecker",String.valueOf(observables.size()));
                    if (observables.size() == 0)
                    {
                        return Observable.just(null);
                    }
                    return Observable.merge(observables);
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnCompleted(() -> {
                    Log.d("HaiChecker","notify");
                    if (databinding.xrefreshView.mPullRefreshing) {
                        databinding.xrefreshView.stopRefresh(true);
                    }
                    adapter.notifyDataSetChanged();
                })
                .subscribe(s -> {
                    Log.d("HaiChecker","接收一次");
                },throwable -> {
                    if (databinding.xrefreshView.mPullRefreshing) {
                        databinding.xrefreshView.stopRefresh(false);
                    }
                    throwable.printStackTrace();
                });
    }


    private void getFileList(boolean isLocal) {
        Log.d("HaiChecker","是否获取本地缓存数据:"+isLocal);
        repository.getFileList(isLocal, "")
                .flatMap(results -> {
                    List<Observable<RxDownLoadManager.RxDownLoadCallBack>> observables = new ArrayList<>();
                    for (FileItemResult result : results) {
                        if (!TextUtils.isEmpty(result.getFile_http_url()))
                        {
                            observables.add(RxDownLoadManager.download(result));
                        }
                    }
//                    data.clear();
//                    data.addAll(results);
                    Log.d("HaiChecker",String.valueOf(observables.size()));
                    if (observables.size() == 0)
                    {
                        return Observable.just(null);
                    }
                    return Observable.merge(observables);
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnCompleted(() -> {
                    Log.d("HaiChecker","notify");
                    if (databinding.xrefreshView.mPullRefreshing) {
                        databinding.xrefreshView.stopRefresh(true);
                    }
                    adapter.notifyDataSetChanged();
                })
                .subscribe(s -> {
                    Log.d("HaiChecker","接收一次");
                },throwable -> {
                    if (databinding.xrefreshView.mPullRefreshing) {
                        databinding.xrefreshView.stopRefresh(false);
                    }
                    throwable.printStackTrace();
                });
    }

    private void delFaq(FaqItemResult faq_id)
    {
        ApiManager.retrofit(getContext())
                .create(AllService.class)
                .delFaq(faq_id.getFaq_id())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(() -> kProgressHUD.setLabel("删除中").show())
                .subscribe(stringBaseHttpResult -> {
                    data.remove(faq_id);
                    kProgressHUD.setLabel("删除成功");
                    new Handler().postDelayed(() -> kProgressHUD.dismiss(),1000);
                    adapter.notifyDataSetChanged();
                },throwable -> {
                    kProgressHUD.setLabel("删除失败");
                    new Handler().postDelayed(() -> kProgressHUD.dismiss(),1000);
                });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        super.onCreateOptionsMenu(menu, inflater);

    }
}
